<?php
/**
 * Copyright (c) 2017. 上海业晋信息技术有限公司 www.yejinsoft.com
 */

namespace App\Http\Controllers\V1\BasicData;

use App\Models\V1\AdminUser;
use Illuminate\Http\Request;
use App\Models\V1\Faculty;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\V1\FacultyRequest;

class FacultiesController extends Controller
{
    /**
     * 显示教职工数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.faculties');
    }

    /**
     * 获取教职工数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的教职工数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        $reqParams = $request->all();
        $year = isset($reqParams['year']) ? $reqParams['year'] : '';
        
        // 获取符合查询条件的教职工数据
        $data = $this->getFacultyList($currentPage, $rows, $keywords, $year);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $objDepartment = $item->department;
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['avatar'] = $item['avatar'];
                    $formatItem['department_code'] = $objDepartment['name'];
                    $formatItem['mobile'] = $item['mobile'];
                    $formatItem['telephone'] = $item['telephone'];
                    $formatItem['email'] = $item['email'];
                    $formatItem['specialty'] = $item['specialty'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条教职工数据显示界面（适用于查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['code'] = $request->input('code');
        $currentStaff = $this->getFacultyByCode($data['code']);
        $objDepartment = $currentStaff->department;
        if ($data['view'] === 'viewData') {
            $currentStaff['avatar'] = empty($currentStaff['avatar']) ? env('APP_URL') . '/images/default.jpg' : $currentStaff['avatar'];
            $currentStaff['department_code'] = $objDepartment['name'];
        }
        $data['itemData'] = $currentStaff;
        return view('v1.form.faculty_item', $data);
    }

    /**
     * 显示教职工数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }

    /**
     * 更新教职工基本信息(单元格)
     *
     * @param FacultyRequest $request
     * @return array
     */
    public function updateCellData(FacultyRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教职工代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateFaculty($request);

            // 更新教职工信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教职工代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新教职工基本信息
     *
     * @param FacultyRequest $request
     * @return array
     */
    public function updateData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教职工代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateFaculty($request);

            // 更新教职工信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教职工代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 删除教职工基本信息
     *
     * @param FacultyRequest $request
     * @return array
     */
    public function deleteData(FacultyRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教职工代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateFaculty($request);

            // 删除教职工信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教职工代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除教职工基本信息
     *
     * @param FacultyRequest $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '教职工批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除教职工信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '教职工批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的教职工列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getFacultyList($page = 1, $rows, $keywords, $year)
    {
        if($year != ''){
            if (!isset($keywords) || empty($keywords)) {
                $data = Faculty::orderBy('updated_at', 'desc')
                        ->where('created_at', 'like', '%'.$year.'%')
                        ->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Faculty::where('name', 'like', '%' . $keywords . '%')->orderBy('updated_at', 'desc')
                        ->where('created_at', 'like', '%'.$year.'%')
                        ->paginate($rows, ['*'], 'page', $page);
            }
        }else{
            if (!isset($keywords) || empty($keywords)) {
                $data = Faculty::orderBy('updated_at', 'desc')->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Faculty::where('name', 'like', '%' . $keywords . '%')->orderBy('updated_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }
        return $data;
    }

    /**
     * 根据教职工代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getFacultyByCode($code)
    {
        $staff = Faculty::where('code', $code)->first();
        return $staff;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新教职工信息验证请求
     *
     * @param Request $request
     */
    private function validateFaculty(FacultyRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新教职工信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
                'mobile' => $request->input('mobile'),
            ];

            if ($request->input('email') !== "") {
                $updateData['email'] = $request->input('email');
            }
            if ($request->input('telephone') !== "") {
                $updateData['telephone'] = $request->input('telephone');
            }
        }

        $rspObj = Faculty::where('code', $where)
            ->update($updateData);

        return $rspObj;
    }

    /**
     * 处理更新教职工信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');

            foreach ($codeList as $code) {
                $rspObj = Faculty::where('code', $code)->delete();
                $rspObj = AdminUser::where('code',$code)->delete();
            }
        } else { // 单条删除
            $rspObj = Faculty::where('code', $where)
                ->delete();
            //删除登录表中的数据
            $rspObj = AdminUser::where('code',$where)->delete();
        }

        return $rspObj;
    }
}
